'''
和谐健康宝宝少儿定期重大疾病保险计划
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json,time
from common.helper import Helper
from pyquery import PyQuery as pq
from threading import Thread


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "和谐健康宝宝少儿定期重大疾病保险计划"

    # 生成产品信息
    def genProductInfo(self):

        plan = {

            # 年龄 1 -10 # 保险期限20年 缴费年限0 3 5 10
            "planA": {

                # 年龄段
                "year": [str(i) for i in range(1, 11)],
                # 性别 0 男 1 女
                "gender": ["0", "1"],
                # 保险期限
                "expire": ["20", "25", "30"],
                # 缴费期限
                "paytime": ["0", "3", "5", "10"],
                # 基本保额
                "money": ["10", "20", "30", "40", "50", "60"],
                # 附加重疾医疗保险 0 不投保 50w保额 100w保额
                "ext_item": ["0", "50", "100"]

            },
            # 年龄 1 -10 保险期限25年 缴费年限0 3 5 10 15
            "planB": {

                # 年龄段
                "year": [str(i) for i in range(1, 11)],
                # 性别 0 男 1 女
                "gender": ["0", "1"],
                # 保险期限
                "expire": ["35"],
                # 缴费期限
                "paytime": ["0", "3", "5", "10", "15"],
                # 基本保额
                "money": ["10", "20", "30", "40", "50", "60"],
                # 附加重疾医疗保险 0 不投保 50w保额 100w保额
                "ext_item": ["0", "50", "100"]

            },
            # 年龄 1 -10 保险期限30年 缴费年限0 3 5 10 15 20
            "planC": {

                # 年龄段
                "year": [str(i) for i in range(1, 11)],
                # 性别 0 男 1 女
                "gender": ["0", "1"],
                # 保险期限
                "expire": ["30"],
                # 缴费期限
                "paytime": ["0", "3", "5", "10", "15", "20"],
                # 基本保额
                "money": ["10", "20", "30", "40", "50", "60"],
                # 附加重疾医疗保险 0 不投保 50w保额 100w保额
                "ext_item": ["0", "50", "100"]

            },
            # 年龄 11 - 15 保险期间20 年 缴费年限 0 3 5 10
            "planD": {

                # 年龄段
                "year": [str(i) for i in range(11, 15)],
                # 性别 0 男 1 女
                "gender": ["0", "1"],
                # 保险期限
                "expire": ["20"],
                # 缴费期限
                "paytime": ["0", "3", "5", "10"],
                # 基本保额
                "money": ["10", "20", "30", "40", "50", "60"],
                # 附加重疾医疗保险 0 不投保 50w保额 100w保额
                "ext_item": ["0", "50", "100"]

            },
            # 年龄 11 - 15 保险期间20 年 缴费年限 0 3 5 10 15
            "planE": {

                # 年龄段
                "year": [str(i) for i in range(11, 15)],
                # 性别 0 男 1 女
                "gender": ["0", "1"],
                # 保险期限
                "expire": ["20"],
                # 缴费期限
                "paytime": ["0", "3", "5", "10", "15"],
                # 基本保额
                "money": ["10", "20", "30", "40", "50", "60"],
                # 附加重疾医疗保险 0 不投保 50w保额 100w保额
                "ext_item": ["0", "50", "100"]

            },
            # 年龄 16 - 17 保险期间20 年 缴费年限  0 3 5 10
            "planF": {

                # 年龄段
                "year": [str(i) for i in range(11, 15)],
                # 性别 0 男 1 女
                "gender": ["0", "1"],
                # 保险期限
                "expire": ["20"],
                # 缴费期限
                "paytime": ["0", "3", "5", "10"],
                # 基本保额
                "money": ["10", "20", "30", "40", "50", "60"],
                # 附加重疾医疗保险 0 不投保 50w保额 100w保额
                "ext_item": ["0", "50", "100"]

            }

        }

        for k in plan:

            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["expire"], plan[k]["paytime"],
                             plan[k]["money"], plan[k]["ext_item"]):
                # 写入数据库
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))
                self.mysql._conn.commit()
                print("%s产品信息写入数据库成功" % self.name)

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):


        if dt["ext_item"] == "0":

            data = {"Insureds": {"Bsex": dt["gender"],
                                 "BbirthDate": "{year}-03-07".format(year=str(2019 - int(dt["year"])))},
                    "Risks": {"partner": [], "RiskCode": 2140342, "insurePeriod": dt["expire"],
                        "payPeriod": 0 if dt["paytime"] == "0" else 12,
                        "payPeriodYear": dt["paytime"],

                        "basicAmount": dt["money"] + "0000"}}

        else:


            data = {"Insureds": {"Bsex": dt["gender"], "BbirthDate": "{year}-03-07".format( year = str(2019-int(dt["year"])))}, "Risks": {"partner": [
                {"ContPlanCode": "2110092", "ContPlanAmnt": "0" if dt["ext_item"] == "0" else dt["ext_item"] + "0000", "prem": 2661.1, "ContPlanName": "附加重疾医疗保额",
                 "referrerCommission": "0"}], "RiskCode": 2140342, "insurePeriod": dt["expire"], "payPeriod": 0 if dt["paytime"] == "0" else 12 ,
                "payPeriodYear": dt["paytime"],

                "basicAmount": dt["money"] + "0000"}}


        try:

            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=json.dumps(data))

            print( r.json( ))

            if r.status_code == 200 and r.json()["operateStr"] == "success":

                price = Helper.decimalParse(r.json()["outputObj"]["prem"])

                data = {

                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }

                mysql.updatePrice( data )


            else:

                data = {

                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }
                mysql.randTask(data)

        except:

            pass


    def main(self, mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt, mysql)

    def startProcess(self):

        threads = []

        for i in range(5):

            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))

            t.start()

            threads.append(t)

        for t in threads:
            t.join()


if __name__ == '__main__':
    s = Spider()
    s.startProcess()